package org.benetech.reader.parser;

import java.util.ArrayList;

import org.benetech.reader.representations.Book;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ParserAPI {

   @SuppressWarnings("null")
   public static ArrayList<Book> parseSearchFTS(String jsonString) {
      ArrayList<Book> bookList = new ArrayList<Book>();

      JSONObject jObject;
      JSONObject jObject2;
      JSONArray jlist = null;
      try {
         jObject2 = new JSONObject(jsonString);
         jObject = jObject2.getJSONObject("bookshare").getJSONObject("book")
               .getJSONObject("list");
         jlist = jObject.getJSONArray("result");
      } catch (JSONException e) {
         e.printStackTrace();
      }

      for (int i = 0; i < jlist.length(); i++) {
         try {
            String[] authors = new String[jlist.getJSONObject(i)
                  .getJSONArray("author").length()];
            String[] formats = new String[jlist.getJSONObject(i)
                  .getJSONArray("downloadFormat").length()];
            JSONArray arr = jlist.getJSONObject(i).getJSONArray("author");
            JSONArray arr2 = jlist.getJSONObject(i).getJSONArray(
                  "downloadFormat");
            for (int j = 0; j < arr.length(); j++)
               authors[j] = arr.getString(j);
            for (int k = 0; k < arr2.length(); k++)
               formats[k] = arr2.getString(k);
            bookList.add(new Book(authors, jlist.getJSONObject(i).getString(
                  "availableToDownload"), jlist.getJSONObject(i).getString(
                  "briefSynopsis"), formats, jlist.getJSONObject(i).getString(
                  "dtbookSize"), jlist.getJSONObject(i).getString(
                  "freelyAvailable"), jlist.getJSONObject(i).getString("id"),
                  jlist.getJSONObject(i).getString("images"), jlist
                        .getJSONObject(i).getString("isbn13"), jlist
                        .getJSONObject(i).getString("publisher"), jlist
                        .getJSONObject(i).getString("title")));

         } catch (JSONException e) {

            e.printStackTrace();
         }

      }
      return bookList;

   }
}
